package com.yyfax.pay.common.util;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.common.base.Joiner;
import com.yyfax.framework.common.Log;
import com.yyfax.framework.service.SequenceService;
import com.yyfax.pay.common.enums.FuiouBusiTypeEnum;
import com.yyfax.pay.common.exception.YYPayException;
import com.yyfax.pay.order.model.vo.PayBusiIdVO;

/**
 * 富友存管业务主键工具
 * 
 * @author heizq
 * @date 2017-09-01 10:26:52
 * @since v1.0.0
 */
@Component
public class FuiouIdUtils {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	/** 步长 */
	private static final int SEQUENCE_STEP = 20;

	/** 长度 */
	private static final int SEQUENCE_LENGH = 30;

	@Resource
	private SequenceService sequenceService;

	/**
	 * 返回30位的不重复业务主键带有商户号
	 * 
	 * @author heizq
	 * @date 2017-09-01 10:34:30
	 * @since v1.0.0
	 * @param fuiouBusiTypeEnum
	 * @param merchantCode 商户号，且商户号，必须为4位
	 * @return
	 */
	public String generateBusiId(FuiouBusiTypeEnum fuiouBusiTypeEnum, String merchantCode) {

		return sequenceService.sequenceStr(fuiouBusiTypeEnum.getKey(),
				Joiner.on("").join(fuiouBusiTypeEnum.getPrefix(), fuiouBusiTypeEnum.getValue(), merchantCode), SEQUENCE_STEP, SEQUENCE_LENGH);
	}

	/**
	 * 根据业务主键id，获取业务类型
	 * 
	 * @author heizq
	 * @date 2017-09-01 17:02:45
	 * @since v1.0.0
	 * @param busiId
	 * @return
	 */
	public PayBusiIdVO parserBusiId(String busiId) {
		if (StringUtils.isBlank(busiId)) {
			return null;
		}

		FuiouBusiTypeEnum type = FuiouBusiTypeEnum.parse(busiId.substring(2, 4));

		if (type == null) {
			logger.warn(Log.op("FuiouIdUtils.parserBusiId").msg("流水号格式异常，无法解析业务类型").kv("busiId", busiId).toString());
			throw new YYPayException("流水号业务类型异常！流水号：" + busiId);
		}

		PayBusiIdVO vo = new PayBusiIdVO();
		vo.setPrefix(busiId.substring(0, 2));
		vo.setBusiType(type);
		vo.setMerchantCode(busiId.substring(4, 8));
		return vo;
	}
}
